package br.com.lambdacore.ui.stripes.converter;

import static br.com.lambdacore.validator.Validator.is;

import java.util.Collection;
import java.util.Locale;

import net.sourceforge.stripes.validation.TypeConverter;
import net.sourceforge.stripes.validation.ValidationError;

import org.apache.commons.lang.StringUtils;

public class LocaleConverter implements TypeConverter<Locale> {

	private Locale locale;

	public Locale convert(String localeAsString, Class<? extends Locale> targetType,
			Collection<ValidationError> errors) {
		if (is(localeAsString).nullOrBlank()) {
			return this.locale;
		}

		String language = "";
		String country = "";
		String variant = "";

		String[] localeSplited = StringUtils.split(localeAsString, "_-");

		if (is(localeSplited).lengthGreaterThan(2)) {
			variant = localeSplited[2];
		}
		if (is(localeSplited).lengthGreaterThan(1)) {
			country = localeSplited[1];
		}
		if (is(localeSplited).lengthGreaterThan(0)) {
			language = localeSplited[0];
		}
		return new Locale(language, country, variant);
	}

	public void setLocale(Locale locale) {
		this.locale = locale;
	};
}
